package com.lastproject.web.bean;

import java.awt.Image;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.sql.Blob;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.event.ComponentSystemEvent;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;
import javax.sql.rowset.serial.SerialBlob;
import javax.sql.rowset.serial.SerialException;

import org.apache.poi.hssf.record.formula.functions.Searchb;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.DefaultStreamedContent;

import com.lastproject.dto.CandidateDTO;
import com.lastproject.dto.ConfidentialEmployeeDTO;
import com.lastproject.dto.DepartmentDTO;
import com.lastproject.dto.EmployeeDTO;
import com.lastproject.dto.TraineeDTO;
import com.lastproject.dto.UserDTO;
import com.lastproject.ejb.dao.CandidateDAORemote;
import com.lastproject.ejb.dao.CheckPermissionDAORemote;
import com.lastproject.ejb.dao.ConfidentialEmployeeDAORemote;
import com.lastproject.ejb.dao.DepartmentDAORemote;
import com.lastproject.ejb.dao.EmployeeDAORemote;
import com.lastproject.ejb.dao.TraineeDAORemote;
import com.lastproject.ejb.dao.UserDAORemote;
import com.lastproject.ejb.util.RoleUtils;

@ManagedBean
@SessionScoped
public class EmployeeBean implements Validator {

	@ManagedProperty(value = "#{searchUserBean}")
	private SearchUserBean searchUserBean;

	private static final String NEW_PASSWORD = "newPassword";

	private final static Logger LOGGER = Logger.getLogger(EmployeeBean.class
			.getName());

	private static final String DATE_FORMAT = "dd.MM.yyyy";
	private boolean basicUser = false; // id 1
	private boolean teamLeader = false; // id 2
	private boolean administration = false; // id 3
	private boolean departmentManager = false; // id 4
	private boolean libraryAdmin = false; // id 5
	private boolean accountant = false; // id 7

	private TraineeDTO updateTrainee;

	private List<Integer> roleIdList = new ArrayList<Integer>();

	private List<EmployeeDTO> teamLeaderList;
	private List<DepartmentDTO> departmentList;
	private List<UserDTO> superiorList;

	private int selectedTeamLeaderId;
	private int selectedDepartmentId;
	private int selectedSuperiorId;

	private boolean renderSalary;

	private String errorMessage = "";
	private String successMessage = "";
	private String departmentManagerMessage;
	private String userType = "";
	private String errorMsg = "";

	private byte[] photo;

	// checkbox for sending mail to new users
	private boolean sendEmail = false;

	// import CSV
	private int counter = 0;

	@EJB
	CheckPermissionDAORemote checkPermissionDAORemote;

	public void preRenderView(ComponentSystemEvent event) {
		if (!(checkPermissionDAORemote.hasCrudOnEmployeesRights(true)
				|| checkPermissionDAORemote.hasEmployeeManagementRights(true)
				|| checkPermissionDAORemote.hasDepartmentManagementRights(true) || checkPermissionDAORemote
					.hasTeamManagementRights(true))) {
			FacesContext fc = FacesContext.getCurrentInstance();
			ExternalContext ec = fc.getExternalContext();
			try {
				ec.redirect("restrictedAccess.xhtml");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	public SearchUserBean getSearchUserBean() {
		return searchUserBean;
	}

	public void setSearchUserBean(SearchUserBean searchUserBean) {
		this.searchUserBean = searchUserBean;
	}

	public byte[] getPhoto() {
		return photo;
	}

	public void setPhoto(byte[] photo) {
		this.photo = photo;
	}

	public boolean isSendEmail() {
		return sendEmail;
	}

	public void setSendEmail(boolean sendEmail) {
		this.sendEmail = sendEmail;
	}

	public int getCounter() {
		return counter;
	}

	public void setCounter(int counter) {
		this.counter = counter;
	}

	public String getErrorMsg() {
		return errorMsg;
	}

	public void setErrorMsg(String errorMsg) {
		this.errorMsg = errorMsg;
	}

	private String updateType = null;

	private Part csv;

	public Part getCsv() {
		return csv;
	}

	public void setCsv(Part csv) {
		this.csv = csv;
	}

	public String getSuccessMessage() {
		return successMessage;
	}

	public void setSuccessMessage(String successMessage) {
		this.successMessage = successMessage;
	}

	public void setUserType(String userType) {
		this.userType = userType;
	}

	private EmployeeDTO currentEmployee;

	private CandidateDTO candidateDTO;

	@ManagedProperty(value = "#{confidentialEmployeeDTO}")
	private ConfidentialEmployeeDTO confidentialEmployeeDTO;

	@ManagedProperty(value = "#{traineeDTO}")
	private TraineeDTO traineeDTO;

	public EmployeeDTO getCurrentEmployee() {
		return currentEmployee;
	}

	public void setCurrentEmployee(EmployeeDTO currentEmployee) {
		this.currentEmployee = currentEmployee;
	}

	public CandidateDTO getCandidateDTO() {
		return candidateDTO;
	}

	public void setCandidateDTO(CandidateDTO candidateDTO) {
		this.candidateDTO = candidateDTO;
	}

	public String getUpdateType() {
		return updateType;
	}

	public void setUpdateType(String updateType) {
		this.updateType = updateType;
	}

	public TraineeDTO getUpdateTrainee() {
		return updateTrainee;
	}

	public void setUpdateTrainee(TraineeDTO updateTrainee) {
		this.updateTrainee = updateTrainee;
	}

	@EJB
	EmployeeDAORemote employeeDAORemote;

	@EJB
	ConfidentialEmployeeDAORemote confidentialEmployeeDAORemote;

	@EJB
	UserDAORemote userDAORemote;

	@EJB
	TraineeDAORemote traineeDAORemote;

	@EJB
	DepartmentDAORemote departmentDAORemote;

	@EJB
	CandidateDAORemote candidateDAORemote;
	private boolean disabled = true;
	private boolean saveRendered = false;
	private boolean currentAdministration;

	public boolean isCurrentAdministration() {
		return currentAdministration;
	}

	public void setCurrentAdministration(boolean currentAdministration) {
		this.currentAdministration = currentAdministration;
	}

	public boolean isDisabled() {
		return disabled;
	}

	public void setDisabled(boolean disabled) {
		this.disabled = disabled;
	}

	public boolean isSaveRendered() {
		return saveRendered;
	}

	public void setSaveRendered(boolean saveRendered) {
		this.saveRendered = saveRendered;
	}

	public String startAddEmployee() {
		resetEmployeeFields();
		searchUserBean.setShowPhoto(false);
		errorMessage = "";
		return "addEmployee.xhtml";
	}

	public String startAddTrainee() {
		resetTraineeFields();
		searchUserBean.setShowPhoto(false);
		errorMessage = "";
		return "addTrainee.xhtml";
	}

	public void resetRoles() {
		basicUser = false;
		teamLeader = false;
		administration = false;
		departmentManager = false;
		libraryAdmin = false;
		accountant = false;

	}

	public void resetEmployeeFields() {
		confidentialEmployeeDTO.setUsername(null);
		confidentialEmployeeDTO.setFirstname(null);
		confidentialEmployeeDTO.setLastname(null);
		confidentialEmployeeDTO.setWorkEmail(null);
		confidentialEmployeeDTO.setDob(null);
		confidentialEmployeeDTO.setPersonalPhone(null);
		confidentialEmployeeDTO.setPersonalEmail(null);
		confidentialEmployeeDTO.setEmploymentDate(null);
		confidentialEmployeeDTO.setMedCheckUpDate(null);
		confidentialEmployeeDTO.setEmploymentType(null);
		confidentialEmployeeDTO.setPosition(null);

		confidentialEmployeeDTO.setCareerLevel(null);
		confidentialEmployeeDTO.setGermanContactPerson(null);
		confidentialEmployeeDTO.setProsisNr(0);
		confidentialEmployeeDTO.setWorkPhone(null);

		confidentialEmployeeDTO.setSalary(null);
		confidentialEmployeeDTO.setVarPart(null);
		confidentialEmployeeDTO.setCv(null);
		confidentialEmployeeDTO.setDepartmentManager(false);
		confidentialEmployeeDTO.setDepartureDate(null);
		confidentialEmployeeDTO.setTeamLeader(false);
		confidentialEmployeeDTO.setIdSuperior(0);

		selectedTeamLeaderId = 0;
		selectedSuperiorId = 0;

		basicUser = false; // id 1
		teamLeader = false; // id 2
		administration = false; // id 3
		departmentManager = false; // id 4
		libraryAdmin = false; // id 5
		accountant = false; // id 7

		errorMessage = "";
		successMessage = "";
		errorMsg = "";

		UserDTO currentUser = (UserDTO) FacesContext.getCurrentInstance()
				.getExternalContext().getSessionMap().get("userDTO");
		ConfidentialEmployeeDTO logged = confidentialEmployeeDAORemote
				.findById(currentUser.getId());
		selectedDepartmentId = logged.getIdDepartment();
		saveRendered = true;
	}

	public void resetTraineeFields() {
		traineeDTO.setId(0);
		traineeDTO.setUsername(null);
		traineeDTO.setFirstname(null);
		traineeDTO.setLastname(null);
		traineeDTO.setWorkEmail(null);
		traineeDTO.setDob(null);
		traineeDTO.setPersonalPhone(null);
		traineeDTO.setPersonalEmail(null);
		traineeDTO.setEmploymentDate(null);
		traineeDTO.setMedCheckUpDate(null);
		traineeDTO.setEmploymentType(null);
		traineeDTO.setPosition(null);
		traineeDTO.setSalary(null);
		traineeDTO.setRolesIdList(null);
		traineeDTO.setPhoto(null);

		selectedTeamLeaderId = 0;
		selectedDepartmentId = 0;
		selectedSuperiorId = 0;

		basicUser = false; // id 1
		errorMessage = "";
		successMessage = "";
		errorMsg = "";
	}

	@PostConstruct
	public void populateLists() {

		teamLeaderList = employeeDAORemote.getTeamLeaders();
		departmentList = departmentDAORemote.getAll();
		superiorList = userDAORemote.getAll();

		renderSalary = true;
	}

	public EmployeeBean() {
	}

	public ConfidentialEmployeeDTO getConfidentialEmployeeDTO() {
		return confidentialEmployeeDTO;
	}

	public void setConfidentialEmployeeDTO(
			ConfidentialEmployeeDTO confidentialEmployeeDTO) {
		this.confidentialEmployeeDTO = confidentialEmployeeDTO;
	}

	public TraineeDTO getTraineeDTO() {
		return traineeDTO;
	}

	public void setTraineeDTO(TraineeDTO traineeDTO) {
		this.traineeDTO = traineeDTO;
	}

	public boolean isBasicUser() {
		return basicUser;
	}

	public void setBasicUser(boolean basicUser) {
		this.basicUser = basicUser;
	}

	public boolean isAdministration() {
		return administration;
	}

	public void setAdministration(boolean administration) {
		this.administration = administration;
	}

	public boolean isDepartmentManager() {
		return departmentManager;
	}

	public void setDepartmentManager(boolean departmentManager) {
		this.departmentManager = departmentManager;
	}

	public boolean isLibraryAdmin() {
		return libraryAdmin;
	}

	public void setLibraryAdmin(boolean libraryAdmin) {
		this.libraryAdmin = libraryAdmin;
	}

	public boolean isTeamLeader() {
		return teamLeader;
	}

	public void setTeamLeader(boolean teamLeader) {
		this.teamLeader = teamLeader;
	}

	public boolean isAccountant() {
		return accountant;
	}

	public void setAccountant(boolean accountant) {
		this.accountant = accountant;
	}

	public boolean isRenderSalary() {
		return renderSalary;
	}

	public void setRenderSalary(boolean renderSalary) {
		this.renderSalary = renderSalary;
	}

	public List<EmployeeDTO> getTeamLeaderList() {
		populateLists();
		return teamLeaderList;
	}

	public List<DepartmentDTO> getDepartmentList() {
		populateLists();
		return departmentList;
	}

	public int getSelectedTeamLeaderId() {
		return selectedTeamLeaderId;
	}

	public void setSelectedTeamLeaderId(int selectedTeamLeaderId) {
		this.selectedTeamLeaderId = selectedTeamLeaderId;
	}

	public int getSelectedDepartmentId() {
		return selectedDepartmentId;
	}

	public void setSelectedDepartmentId(int selectedDepartmentId) {
		this.selectedDepartmentId = selectedDepartmentId;
	}

	public List<UserDTO> getSuperiorList() {
		populateLists();
		return superiorList;
	}

	public int getSelectedSuperiorId() {
		return selectedSuperiorId;
	}

	public void setSelectedSuperiorId(int selectedSuperiorId) {
		this.selectedSuperiorId = selectedSuperiorId;
	}

	public String getErrorMessage() {
		return errorMessage;
	}

	public void setErrorMessage(String errorMessage) {
		this.errorMessage = errorMessage;
	}

	public String getDepartmentManagerMessage() {
		return departmentManagerMessage;
	}

	public void setDepartmentManagerMessage(String departmentManagerMessage) {
		this.departmentManagerMessage = departmentManagerMessage;
	}

	public void photoSave(FileUploadEvent event) throws ParseException {

		try {
			InputStream is = event.getFile().getInputstream();
			int i = is.available();
			byte[] b = new byte[i];

			is.read(b);
			if (b.length != 0) {
				photo = b;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * take the CSV file and parse the data line by line
	 * 
	 * @param event
	 * @throws ParseException
	 */
	public String handleFileUpload(FileUploadEvent event) throws ParseException {
		errorMessage = "";

		try {

			InputStream inputStream = event.getFile().getInputstream();
			InputStreamReader is = new InputStreamReader(inputStream);
			BufferedReader br = new BufferedReader(is);
			String read = null;
			int rowCounter = 0;
			while ((read = br.readLine()) != null) {
				rowCounter++;
				try {

					ConfidentialEmployeeDTO newConfidentialEmployee = new ConfidentialEmployeeDTO();

					String[] token = read.split(";");
					String username = token[0];
					String firstName = token[1];
					String lastName = token[2];
					String workEmail = token[3];
					String dob = token[4];
					String personalPhone = token[5];
					String personalEmail = token[6];
					String employmentDate = token[7];
					String medicalDate = token[8];
					String employmentType = token[9];
					String position = token[10];
					String prosis = token[11];
					String workPhone = token[12];
					String germanContact = token[13];
					String careerLevel = token[14];
					String baseSalary = token[15];
					String variableSalary = token[16];
					String department = token[17];

					newConfidentialEmployee.setUsername(username);
					newConfidentialEmployee.setPassword(username);
					newConfidentialEmployee.setStatusPassword(NEW_PASSWORD);
					newConfidentialEmployee.setFirstname(firstName);
					newConfidentialEmployee.setLastname(lastName);
					newConfidentialEmployee.setWorkEmail(workEmail);

					Date date1 = new SimpleDateFormat(DATE_FORMAT,
							Locale.ENGLISH).parse(dob);

					newConfidentialEmployee.setDob(date1);
					newConfidentialEmployee.setPersonalPhone(personalPhone);
					newConfidentialEmployee.setPersonalEmail(personalEmail);
					Date date2 = new SimpleDateFormat(DATE_FORMAT,
							Locale.ENGLISH).parse(employmentDate);
					newConfidentialEmployee.setEmploymentDate(date2);
					Date date3 = new SimpleDateFormat(DATE_FORMAT,
							Locale.ENGLISH).parse(medicalDate);
					newConfidentialEmployee.setMedCheckUpDate(date3);
					newConfidentialEmployee.setEmploymentType(employmentType);
					newConfidentialEmployee.setPosition(position);
					newConfidentialEmployee.setProsisNr(Integer
							.parseInt(prosis));
					newConfidentialEmployee.setWorkPhone(workPhone);
					newConfidentialEmployee
							.setGermanContactPerson(germanContact);
					newConfidentialEmployee.setCareerLevel(careerLevel);
					newConfidentialEmployee.setSalary(Float
							.parseFloat(baseSalary));
					newConfidentialEmployee.setVarPart(Float
							.parseFloat(variableSalary));
					DepartmentDTO currentDepartment = departmentDAORemote
							.findByName(department);
					newConfidentialEmployee.setIdDepartment(currentDepartment
							.getId());

					// basic user
					roleIdList.clear();
					roleIdList.add(1);
					newConfidentialEmployee.setRolesIdList(roleIdList);

					errorMessage = "";
					try {
						if (!userDAORemote
								.existentUsername(newConfidentialEmployee
										.getUsername())
								&& !userDAORemote
										.existentWorkemail(newConfidentialEmployee
												.getWorkEmail())) {
							LOGGER.log(Level.INFO, "Marked for email: "
									+ sendEmail);
							if (sendEmail == true) {

								confidentialEmployeeDAORemote
										.create(newConfidentialEmployee);
								counter++;
							} else {
								confidentialEmployeeDAORemote
										.createNoEmailSend(newConfidentialEmployee);
								// count the number of users added

								counter++;
							}
						} else {
							errorMessage = "One or more of the usernames is duplicate!";
							// list the mail of the users that where not added
							// successfully
							LOGGER.log(Level.INFO, "Cannot add: " + rowCounter);

						}
					} catch (Exception e) {
						errorMessage = "Invalid Data!";

					}
				} catch (Exception e) {
					errorMessage = "Invalid Data when parsing!";
					LOGGER.log(Level.INFO, "Cannot add row: " + rowCounter, e);
				}
			}

			inputStream.close();
		} catch (IOException e) {

			e.printStackTrace();

		}

		errorMessage = "Successfully added to database!";
		return "addEmployeeFromCSV.xhtml";
	}

	/**
	 * adds a confidentionalEmployee OR Trainee in the database
	 * 
	 * @return null string
	 * @throws Exception
	 */

	public String resetImport() {

		errorMessage = "";
		counter = 0;
		sendEmail = false;

		return "addEmployeeFromCSV.xhtml";
	}

	public String addEmployee() throws Exception {

		FacesContext ctx = FacesContext.getCurrentInstance();
		ExternalContext ectx = ctx.getExternalContext();
		HttpServletRequest request = (HttpServletRequest) ectx.getRequest();

		String userType = request.getParameter("cicic");

		try {

			InputStream is = request.getPart("formAddUser:uploadedFile")
					.getInputStream();
			int i = is.available();
			byte[] b = new byte[i];

			is.read(b);

			switch (userType) {

			case "employee":

				if (photo != null)
					confidentialEmployeeDTO.setPhoto(photo);
				if (b.length != 0) {
					// add
					confidentialEmployeeDTO.setCv(b);
				} else {
					// update

				}

				confidentialEmployeeDTO.setIdDepartment(selectedDepartmentId);
				confidentialEmployeeDTO.setIdSuperior(selectedSuperiorId);

				roleIdList.clear();

				if (basicUser) {
					roleIdList.add(1);
				} else {
					if (roleIdList.contains(RoleUtils.ROLE_ID_BASIC_USER)) {
						roleIdList.remove(roleIdList.indexOf(1));
					}
				}

				if (selectedTeamLeaderId == 0) {
					confidentialEmployeeDTO.setTeamLeader(false);
				}
				if (selectedTeamLeaderId == 1) {
					// employee has team lead role
					confidentialEmployeeDTO.setTeamLeader(true);
					roleIdList.add(2);
				} else {
					// employee has a team lead
					confidentialEmployeeDTO
							.setIdTeamLeader(selectedTeamLeaderId);

					if (roleIdList.contains(RoleUtils.ROLE_ID_TEAMLEADER)) {
						roleIdList.remove(roleIdList.indexOf(2));
					}
				}

				if (administration) {
					roleIdList.add(3);
				} else {
					if (roleIdList.contains(RoleUtils.ROLE_ID_ADMINISTRATOR)) {
						roleIdList.remove(roleIdList.indexOf(3));
					}
				}

				if (departmentManager) {
					confidentialEmployeeDTO.setDepartmentManager(true);
					roleIdList.add(4);
				} else {
					if (roleIdList.contains(RoleUtils.ROLE_ID_DEP_MANAGER)) {
						roleIdList.remove(roleIdList.indexOf(4));
					}
				}

				if (libraryAdmin) {
					roleIdList.add(5);
				} else {
					if (roleIdList.contains(RoleUtils.ROLE_ID_LIBRARY_ADMIN)) {
						roleIdList.remove(roleIdList.indexOf(5));
					}
				}

				if (accountant) {
					roleIdList.add(7);
				} else {
					if (roleIdList.contains(RoleUtils.ROLE_ID_ACCOUNTANT)) {
						roleIdList.remove(roleIdList.indexOf(7));
					}
				}
				confidentialEmployeeDTO.setRolesIdList(roleIdList);

				if (confidentialEmployeeDAORemote
						.findById(confidentialEmployeeDTO.getId()) != null) { // user
					// with given id is found in db // edit their info
					confidentialEmployeeDAORemote.edit(confidentialEmployeeDTO);
					updateType = null;
				}

				else

				{ // user with given id is not found // add it
					successMessage = "";
					errorMsg = "";

					if (!userDAORemote.existentUsername(confidentialEmployeeDTO
							.getUsername())
							&& !userDAORemote
									.existentWorkemail(confidentialEmployeeDTO
											.getWorkEmail())) {
						confidentialEmployeeDTO
								.setPassword(confidentialEmployeeDTO
										.getUsername());
						confidentialEmployeeDTO.setStatusPassword(NEW_PASSWORD);
						confidentialEmployeeDTO.setEnabled(false);
						if (photo != null)
							confidentialEmployeeDTO.setPhoto(photo);
						confidentialEmployeeDAORemote
								.create(confidentialEmployeeDTO);
						// reset all fields
						resetEmployeeFields();
						successMessage = "Employee successfully added!";
					} else {
						errorMsg = "Username or work email already exists!";
					}
				}

				break;

			case "trainee":

				traineeDTO.setCv(b);
				if (photo != null)
					traineeDTO.setPhoto(photo);
				roleIdList.clear();
				if (basicUser) {
					roleIdList.add(8);
				} else {
					if (roleIdList.contains(RoleUtils.ROLE_ID_LIMITED_USER)) {
						roleIdList.remove(roleIdList.indexOf(8));
					}
				}

				traineeDTO.setRolesIdList(roleIdList);
				try {
					traineeDAORemote.findById(traineeDTO.getId());
					traineeDAORemote.edit(traineeDTO);
					updateType = null;
				} catch (Exception e) {
					// user with given id is found in db // edit their info

					// user with given id is not found //add it
					successMessage = "";
					errorMsg = "";

					if (!userDAORemote.existentUsername(traineeDTO
							.getUsername())
							&& !userDAORemote.existentWorkemail(traineeDTO
									.getWorkEmail())) {
						if (photo != null)
							traineeDTO.setPhoto(photo);
						traineeDTO.setPassword(traineeDTO.getUsername());
						traineeDTO.setStatusPassword(NEW_PASSWORD);
						traineeDTO.setEnabled(false);
						traineeDAORemote.create(traineeDTO);
						// reset all fields
						resetTraineeFields();
						successMessage = "Trainee successfully added!";
					} else {
						errorMsg = "Username or work email already exists!";
					}
				}

				break;
			default:
			}

		} catch (IOException e) {
			e.printStackTrace();
		} catch (ServletException e) {
			e.printStackTrace();
		}
		return null;
	}

	public String updateUsers() {

		FacesContext ctx = FacesContext.getCurrentInstance();
		ExternalContext ectx = ctx.getExternalContext();
		HttpServletRequest request = (HttpServletRequest) ectx.getRequest();

		int selectedUserId = Integer.parseInt(request.getParameter("updateId"));

		updateType = request.getParameter("updateType");

		String returnPage = "";

		switch (updateType) {

		case "ConfidentialEmployee":

			ConfidentialEmployeeDTO c = confidentialEmployeeDAORemote
					.findById(selectedUserId);

			confidentialEmployeeDTO.setId(c.getId());
			confidentialEmployeeDTO.setFirstname(c.getFirstname());
			confidentialEmployeeDTO.setLastname(c.getLastname());
			confidentialEmployeeDTO.setUsername(c.getUsername());
			confidentialEmployeeDTO.setPassword(c.getPassword());
			confidentialEmployeeDTO.setEnabled(c.isEnabled());
			confidentialEmployeeDTO.setWorkEmail(c.getWorkEmail());
			confidentialEmployeeDTO.setDob(c.getDob());
			confidentialEmployeeDTO.setPersonalPhone(c.getPersonalPhone());
			confidentialEmployeeDTO.setPersonalEmail(c.getPersonalEmail());
			confidentialEmployeeDTO.setEmploymentDate(c.getEmploymentDate());
			confidentialEmployeeDTO.setMedCheckUpDate(c.getMedCheckUpDate());
			confidentialEmployeeDTO.setEmploymentType(c.getEmploymentType());
			confidentialEmployeeDTO.setPosition(c.getPosition());
			confidentialEmployeeDTO.setCv(c.getCv());
			confidentialEmployeeDTO.setProsisNr(c.getProsisNr());
			confidentialEmployeeDTO.setWorkPhone(c.getWorkPhone());
			confidentialEmployeeDTO.setGermanContactPerson(c
					.getGermanContactPerson());
			confidentialEmployeeDTO.setCareerLevel(c.getCareerLevel());
			confidentialEmployeeDTO.setRolesIdList(c.getRolesIdList());
			confidentialEmployeeDTO.setSalary(c.getSalary());
			confidentialEmployeeDTO.setVarPart(c.getVarPart());
			confidentialEmployeeDTO.setPhoto(c.getPhoto());

			if (c.isTeamLeader())
				selectedTeamLeaderId = 1;
			else
				selectedTeamLeaderId = c.getIdTeamLeader();

			selectedSuperiorId = c.getIdSuperior();

			selectedDepartmentId = c.getIdDepartment();
			resetRoles();

			UserDTO currentUser = (UserDTO) FacesContext.getCurrentInstance()
					.getExternalContext().getSessionMap().get("userDTO");
			ConfidentialEmployeeDTO ce = confidentialEmployeeDAORemote
					.findById(currentUser.getId());

			currentAdministration = ce.getRolesIdList().contains(
					RoleUtils.ROLE_ID_ADMINISTRATOR)
					|| ce.getRolesIdList().contains(
							RoleUtils.ROLE_ID_SUPERADMIN); // administration or
															// superadmin

			List<Integer> currentUserRoles = ce.getRolesIdList();
			if (currentUserRoles.contains(RoleUtils.ROLE_ID_SUPERADMIN)
					|| (ce.isDepartmentManager() && ce.getIdDepartment() == selectedDepartmentId)
					|| currentUserRoles
							.contains(RoleUtils.ROLE_ID_ADMINISTRATOR)) {
				saveRendered = true;
			} else {
				saveRendered = false;
			}

			if (currentUserRoles.contains(RoleUtils.ROLE_ID_ACCOUNTANT)
					|| currentUserRoles.contains(RoleUtils.ROLE_ID_SUPERADMIN)
					|| (ce.isDepartmentManager() && ce.getIdDepartment() == selectedDepartmentId)) {
				renderSalary = true;
			} else {
				renderSalary = false;
			}

			// saveRendered|=currentAdministration;
			roleIdList = confidentialEmployeeDTO.getRolesIdList();

			if (roleIdList.size() != 0) {
				for (int i = 0; i < roleIdList.size(); i++) {
					if (roleIdList.get(i) == RoleUtils.ROLE_ID_BASIC_USER) {
						basicUser = true;
					} else if (roleIdList.get(i) == RoleUtils.ROLE_ID_TEAMLEADER) {
						teamLeader = true;
					} else if (roleIdList.get(i) == RoleUtils.ROLE_ID_ADMINISTRATOR) {
						administration = true;
					} else if (roleIdList.get(i) == RoleUtils.ROLE_ID_DEP_MANAGER) {
						departmentManager = true;
					} else if (roleIdList.get(i) == RoleUtils.ROLE_ID_LIBRARY_ADMIN) {
						libraryAdmin = true;
					} else if (roleIdList.get(i) == RoleUtils.ROLE_ID_ACCOUNTANT) {
						accountant = true;
					}
				}
			} else {
			}

			returnPage = "addEmployee";
			break;

		case "Trainee":

			TraineeDTO t = traineeDAORemote.findById(selectedUserId);

			traineeDTO.setId(t.getId());
			traineeDTO.setFirstname(t.getFirstname());
			traineeDTO.setLastname(t.getLastname());
			traineeDTO.setUsername(t.getUsername());
			traineeDTO.setPassword(t.getPassword());
			traineeDTO.setEnabled(t.isEnabled());
			traineeDTO.setWorkEmail(t.getWorkEmail());
			traineeDTO.setDob(t.getDob());
			traineeDTO.setPersonalPhone(t.getPersonalPhone());
			traineeDTO.setPersonalEmail(t.getPersonalEmail());
			traineeDTO.setEmploymentDate(t.getEmploymentDate());
			traineeDTO.setMedCheckUpDate(t.getMedCheckUpDate());
			traineeDTO.setEmploymentType(t.getEmploymentType());
			traineeDTO.setPosition(t.getPosition());
			traineeDTO.setPhoto(t.getPhoto());

			traineeDTO.setCv(t.getCv());

			traineeDTO.setSalary(t.getSalary());
			traineeDTO.setRolesIdList(t.getRolesIdList());
			traineeDTO.setSalary(t.getSalary());

			roleIdList = traineeDTO.getRolesIdList();

			resetRoles();
			if (roleIdList.size() != 0) {
				for (int i = 0; i < roleIdList.size(); i++) {
					if (roleIdList.get(i) == 1) {
						basicUser = true;
					} else if (roleIdList.get(i) == 2) {
						teamLeader = true;
					} else if (roleIdList.get(i) == 3) {
						administration = true;
					} else if (roleIdList.get(i) == 4) {
						departmentManager = true;
					} else if (roleIdList.get(i) == 5) {
						libraryAdmin = true;
					} else if (roleIdList.get(i) == 7) {
						accountant = true;
					}
				}
			} else {
			}
			errorMessage = "";
			returnPage = "addTrainee";
			break;

		}
		return returnPage;

	}

	/**
	 * Validates the upload CSV form field
	 * 
	 * @param context
	 * @param component
	 * @param value
	 * @throws ValidatorException
	 */

	public void validateCSV(FacesContext context, UIComponent component,
			Object value) throws ValidatorException {

		List<FacesMessage> msgs = new ArrayList<FacesMessage>();
		Part file = (Part) value;

		errorMessage = "";
		if (!"application/vnd.ms-excel".equals(file.getContentType())) {
			if (updateType == null) {
				msgs.add(new FacesMessage("not a csv"));
				errorMessage = "Not a csv";
			} else {
				// this is update
				errorMessage = "";
			}
		}

		if (!msgs.isEmpty()) {
			throw new ValidatorException(msgs);
		}

	}

	/**
	 * Validates the upload PDF form field
	 */
	@Override
	public void validate(FacesContext context, UIComponent component,
			Object value) throws ValidatorException {

		List<FacesMessage> msgs = new ArrayList<FacesMessage>();
		Part file = (Part) value;

		errorMessage = "";

		if (!file.getContentType().equals("application/octet-stream")) {
			if (!"application/pdf".equals(file.getContentType())
					&& !"application/msword".equals(file.getContentType())) {
				if (updateType == null) {
					// this is an add
					msgs.add(new FacesMessage("not a pdf"));
					errorMessage = "Not a pdf or doc";
				} else {
					// this is update
					errorMessage = "";
				}
			}
		}

		if (!msgs.isEmpty()) {
			throw new ValidatorException(msgs);
		}

	}

	public String addEmployeePage() {
		String id = FacesContext.getCurrentInstance().getExternalContext()
				.getRequestParameterMap().get("id");

		candidateDTO = candidateDAORemote.findById(Integer.parseInt(id));
		candidateDTO.setStatut("accepted");

		candidateDAORemote.edit(candidateDTO);

		String firstname = FacesContext.getCurrentInstance()
				.getExternalContext().getRequestParameterMap().get("firstname");
		String lastname = FacesContext.getCurrentInstance()
				.getExternalContext().getRequestParameterMap().get("lastname");

		candidateDTO = candidateDAORemote.findByFullName(firstname, lastname);
		confidentialEmployeeDTO.setFirstname(candidateDTO.getFirstname());
		confidentialEmployeeDTO.setLastname(candidateDTO.getLastname());
		confidentialEmployeeDTO.setDob(candidateDTO.getBirthdate());
		confidentialEmployeeDTO.setPersonalPhone(candidateDTO.getPhoneNr());
		confidentialEmployeeDTO.setPersonalEmail(candidateDTO.getEmail());

		return "addEmployee";
	}

	public String takeUserType() {

		UserDTO currentUser = (UserDTO) FacesContext.getCurrentInstance()
				.getExternalContext().getSessionMap().get("userDTO");
		ConfidentialEmployeeDTO ceUpdate = null;
		// TraineeDTO tUpdate = null;
		try {
			ceUpdate = confidentialEmployeeDAORemote.findById(currentUser
					.getId());
		} catch (Exception e) {
			// not found
		}

		if (ceUpdate != null) {
			currentEmployee = employeeDAORemote.findById(currentUser.getId());
			return "updateEmployee.xhtml";
		} else {
			updateTrainee = traineeDAORemote.findById(currentUser.getId());
			return "updateTrainee.xhtml";
		}

	}

	public String updateProfileEmployee() throws IOException, ServletException {

		UserDTO currentUser = (UserDTO) FacesContext.getCurrentInstance()
				.getExternalContext().getSessionMap().get("userDTO");
		EmployeeDTO auxEmployee = employeeDAORemote.findById(currentUser
				.getId());
		FacesContext ctx = FacesContext.getCurrentInstance();
		ExternalContext ectx = ctx.getExternalContext();
		HttpServletRequest request = (HttpServletRequest) ectx.getRequest();
		errorMessage = "";
		if (request.getPart("getType:uploadedFile") != null) {
			if (!"application/pdf".equals(request.getPart(
					"getType:uploadedFile").getContentType())) {
				errorMessage = "not a pfd";
			} else {
				errorMessage = "";
				InputStream is = request.getPart("getType:uploadedFile")
						.getInputStream();
				int i = is.available();
				byte[] b = new byte[i];

				is.read(b);

				if (b.length != 0) {
					// add
					auxEmployee.setCv(b);
				}
			}
		}

		auxEmployee.setId(currentUser.getId());
		if (photo != null) {
			auxEmployee.setPhoto(photo);
		}
		auxEmployee.setPersonalPhone(currentEmployee.getPersonalPhone());
		auxEmployee.setPersonalEmail(currentEmployee.getPersonalEmail());
		auxEmployee.setWorkPhone(currentEmployee.getWorkPhone());
		auxEmployee.setGermanContactPerson(currentEmployee
				.getGermanContactPerson());

		employeeDAORemote.edit(auxEmployee);

		return "updateEmployee.xhtml";
	}

	public String updateProfileTrainee() throws IOException, ServletException {

		UserDTO currentUser = (UserDTO) FacesContext.getCurrentInstance()
				.getExternalContext().getSessionMap().get("userDTO");

		TraineeDTO auxTrainee = traineeDAORemote.findById(currentUser.getId());
		FacesContext ctx = FacesContext.getCurrentInstance();
		ExternalContext ectx = ctx.getExternalContext();
		HttpServletRequest request = (HttpServletRequest) ectx.getRequest();
		errorMessage = "";
		if (request.getPart("getType:uploadedFile") != null) {
			if (!"application/pdf".equals(request.getPart(
					"getType:uploadedFile").getContentType())) {
				errorMessage = "not a pfd";
			} else {
				errorMessage = "";
				InputStream is = request.getPart("getType:uploadedFile")
						.getInputStream();
				int i = is.available();
				byte[] b = new byte[i];

				is.read(b);

				if (b.length != 0) {
					// add
					auxTrainee.setCv(b);
				}
			}
		}
		auxTrainee.setId(currentUser.getId());
		auxTrainee.setPersonalPhone(updateTrainee.getPersonalPhone());
		auxTrainee.setPersonalEmail(updateTrainee.getPersonalEmail());

		traineeDAORemote.edit(auxTrainee);

		return "updateTrainee.xhtml";
	}

	public void updateProfile() throws IOException, ServletException {
		FacesContext ctx = FacesContext.getCurrentInstance();
		ExternalContext ectx = ctx.getExternalContext();
		HttpServletRequest request = (HttpServletRequest) ectx.getRequest();
		errorMessage = "";
		if (request.getPart("formAddUser:uploadedFile") != null) {
			if (!"application/pdf".equals(request.getPart(
					"formAddUser:uploadedFile").getContentType())) {
				errorMessage = "not a pfd";
			} else {
				errorMessage = "";
				InputStream is = request.getPart("formAddUser:uploadedFile")
						.getInputStream();
				int i = is.available();
				byte[] b = new byte[i];

				is.read(b);

				if (b.length != 0) {
					// add
					currentEmployee.setCv(b);
				}
			}
		}
		UserDTO user = userDAORemote.findById(currentEmployee.getId());
		user.setPersonalPhone(currentEmployee.getPersonalPhone());
		user.setPersonalEmail(currentEmployee.getPersonalEmail());
		userDAORemote.edit(user);
		employeeDAORemote.edit(currentEmployee);
	}

	public DefaultStreamedContent getByteArrayString() throws SerialException,
			SQLException {
		Blob imageBlob1 = new SerialBlob(confidentialEmployeeDTO.getPhoto());
		InputStream stream = imageBlob1.getBinaryStream();
		DefaultStreamedContent image = new DefaultStreamedContent(stream,
				"image/jpg");
		return image;

	}

	public DefaultStreamedContent getByteArrayStringTrainee()
			throws SerialException, SQLException {
		Blob imageBlob1 = new SerialBlob(traineeDTO.getPhoto());
		InputStream stream = imageBlob1.getBinaryStream();
		DefaultStreamedContent image = new DefaultStreamedContent(stream,
				"image/jpg");
		return image;

	}

	public DefaultStreamedContent getByteArrayStringCurrent()
			throws SerialException, SQLException {
		Blob imageBlob1 = new SerialBlob(currentEmployee.getPhoto());
		InputStream stream = imageBlob1.getBinaryStream();
		DefaultStreamedContent image = new DefaultStreamedContent(stream,
				"image/jpg");
		return image;

	}

	public DefaultStreamedContent getByteArraySearch(int id)
			throws SerialException, SQLException {
		if (id != 0) {
			UserDTO userDTO = userDAORemote.findById(id);

			System.out.println("idddddd" + id);
			if (userDTO.getPhoto() != null) {
				Blob imageBlob1 = new SerialBlob(userDTO.getPhoto());
				InputStream stream = imageBlob1.getBinaryStream();
				DefaultStreamedContent image = new DefaultStreamedContent(
						stream, "image/jpg");
				return image;

			}
		}
		return null;
	}

}
